package com.sprite.framework.entity.script;

import java.util.LinkedList;
import java.util.List;

import com.sprite.framework.entity.DataScriptStatement;
import com.sprite.framework.entity.EntityException;
import com.sprite.framework.entity.condition.MultiOperateValue;
import com.sprite.framework.entity.model.ModelEntity;
import com.sprite.framework.entity.model.ModelEntityUtil;
import com.sprite.framework.entity.model.ModelEntityView;
import com.sprite.framework.entity.model.ModelField;

/**
 * 实体别名
 * @author Jack
 */
public final class EntityAlias implements EntityFieldAliasBuilder, MultiOperateValue{
	private  String entityName;
	private  String entityAlias;
	
	private  ModelEntity modelEntity;
	
	protected EntityAlias(String entityName, String entityAlias) {
		this.entityName = entityName;
		this.entityAlias = entityAlias;
		modelEntity = ModelEntityUtil.getModelEntity(entityName);
	}
	
	public String getEntityName() {
		return entityName;
	}
	public String getEntityAlias() {
		return entityAlias;
	}

	public ModelEntity getModelEntity() {
		return modelEntity;
	}
	
	@Override
	public EntityFieldAlias buildFieldAlias(String fieldName, String fieldAlias, EntityScriptFunction function) {
		EntityFieldAlias fiAlias = new EntityFieldAlias(entityAlias, fieldName, fieldAlias, function, null);
		fiAlias.setModelField(modelEntity.getModelField(fieldName));
		return fiAlias;
	}

	@Override
	public List<EntityFieldAlias> buildAllFieldAlias() {
		List<EntityFieldAlias> list = new LinkedList<>();
		for(ModelField modelField : modelEntity.getFields()) {
			list.add(buildFieldAlias(modelField.getFieldName(), modelField.getFieldName(), null));
		}
		return list;
	}

	@Override
	public boolean hasField(String field) {
		return modelEntity.hasField(field);
	}

	@Override
	public String resolveFieldPath(String path)  {
		String entityAlias = null;
		String field = path;

		{
			int i = path.lastIndexOf(".");
			if(i > 0){
				entityAlias = path.substring(0, i);
				field = path.substring(i+1);
			}
		}
		
		if(entityAlias != null) {
			return String.format("%s.%s",entityAlias, modelEntity.getModelField(field).getColName());
		}
		
		return modelEntity.getModelField(field).getColName();
	}

	@Override
	public void makeStatement(DataScriptStatement statement, ModelEntityView modelViewEntity) throws EntityException {
		statement.append(modelEntity.getTableName());
	}
}
